/** 商品管理页面组件 */
import React, { Component } from 'react'

import './Goods.css'
import store from '../store'

import { connect } from "react-redux"
import * as actions from '../store/goods/goodsCreator'
import { bindActionCreators } from 'redux'

import { findAll } from '../api/goodsApi'

class Goods extends Component {

  constructor() {
    super()
    // 初始化组件数据(页面还再渲染的时候请求已经发送，节省资源和时间)
    // findAll().then(response => {
    //   console.log(response, "请求数据")
    //   this.props.goodsInitAction(response.data)
    // })

    // 当前组件使用的商品数据
    this.state = {
      rGoodsList: []
    }
  }

  componentDidMount() {
    // 初始化数据(告诉redux需要初始化数据，不再负责发送请求)
    this.props.goodsInitAction()

    // setTimeout(() => {
    //   this.props.goodsList.then(result => {
    //     console.log(result, "读取store数据")
    //     this.setState({
    //       rGoodsList: [...result]
    //     })
    //   })
    // }, 200)

    // 刷新页面
    store.subscribe(() => {
      // redux中的数据一旦更新，刷新页面
      this.setState({})
    })
  }

  render() {


    return (
      <div>
        <h3>商品数据管理</h3>
        <table cellPadding={10} cellSpacing={0}>
          <thead>
            <tr>
              <th>序号</th>
              <th>名称</th>
              <th>单价</th>
              <th>库存</th>
              <th>描述</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {
              this.props.goodsList.map(goods => (
                <tr key={goods.id}>
                  <td>{goods.id}</td>
                  <td>{goods.gname}</td>
                  <td>{goods.gprice}</td>
                  <td>{goods.gstock}</td>
                  <td>{goods.ginfor}</td>
                  <td>
                    <button>编辑</button>
                    <button>删除</button>
                  </td>
                </tr>
              ))
            }

            {/* 异步数据加载 */}
            {/* {
              this.state.rGoodsList.map(goods => (
                <tr key={goods.id}>
                  <td>{goods.id}</td>
                  <td>{goods.gname}</td>
                  <td>{goods.gprice}</td>
                  <td>{goods.gstock}</td>
                  <td>{goods.ginfor}</td>
                  <td>
                    <button>编辑</button>
                    <button>删除</button>
                  </td>
                </tr>
              ))
            } */}
          </tbody>
        </table>
      </div>
    )
  }
}

const mapState = state => {
  return {
    goodsList: state.goods
  }
}

const mapActions = dispatch => bindActionCreators(actions, dispatch)

export default connect(
  mapState,
  mapActions
)(Goods)